package com.olddriver.crm.web.controller;

import com.olddriver.crm.domain.Systemlog;
import com.olddriver.crm.page.PageResult;
import com.olddriver.crm.query.LogQueryObject;
import com.olddriver.crm.service.ISystemlogService;
import com.olddriver.crm.util.JsonResult;
import jxl.Workbook;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("log")
public class LogContorller {
    @Autowired
    private ISystemlogService systemlogService;

    @RequestMapping("list")
    public String list() {
        return "log/list";
    }

    @RequestMapping("query")
    @ResponseBody
    public PageResult query(LogQueryObject qo) {
        PageResult query = systemlogService.query(qo);
        return systemlogService.query(qo);
    }

    @RequestMapping("deleteAll")
    @ResponseBody
    public JsonResult deleteAll(LogQueryObject qo) {
        systemlogService.deleteAll(qo);
        return JsonResult.success();
    }

    @RequestMapping("export")
    public void exportLog(HttpServletResponse resp) throws Exception {
        resp.setHeader("Content-Disposition", "attachment;filename=log.xls");
        List<Systemlog> systemlogs = systemlogService.listAll();
        if (systemlogs != null && systemlogs.size() != 0) {
            WritableWorkbook workbook = Workbook.createWorkbook(resp.getOutputStream());
            WritableSheet sheet = workbook.createSheet("日志", 0);
            sheet.addCell(new Label(0, 0, "操作用户"));
            sheet.addCell(new Label(1, 0, "操作时间"));
            sheet.addCell(new Label(2, 0, "IP地址"));
            sheet.addCell(new Label(3, 0, "操作明细"));
            sheet.addCell(new Label(3, 0, "操作参数"));
            int i = 1;
            for (Systemlog systemlog : systemlogs) {
                sheet.addCell(new Label(0, i, systemlog.getOpuser().getRealname()));

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sheet.addCell(new DateTime(1, i, dateFormat.parse(systemlog.getOptime().toString()), DateTime.GMT));
                sheet.addCell(new Label(2, i, systemlog.getOpip()));
                sheet.addCell(new Label(3, i, systemlog.getFunction()));
                sheet.addCell(new Label(3, i, systemlog.getParams()));
                i++;
            }

            workbook.write();
            workbook.close();
        }
    }

}
